package com.czp.mall.order.service;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.czp.mall.order.pojo.Item;

@Service
public class ItemService {

	// 商品微服务地址 http://localhost:8081/
	/*
	 * 如何调用远程服务：
	 * 	1、使用HttpClient
	 *  2、使用OkHttp
	 *  3、Spring Boot提供了RestTemplate进行远程调用
	 */
	
	@Autowired
	private RestTemplate restTemplate;
	
	
	@Autowired
	private DiscoveryClient discoveryClient;
	
	@Autowired
	private LoadBalancerClient loadBalancerClient;
	
	@Value("${server.item}")
	private String itemServerPath;
	
	public Item queryItemById(Long id) {
//		List<ServiceInstance> instances = discoveryClient.getInstances("czp-mall-item");
//		if (instances == null || instances.isEmpty()) {
//			return null;
//		}
//		
//		ServiceInstance serviceInstance = instances.get(0);
//		// 拼接地址
//		String path = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort();
//		Item item = restTemplate.getForObject(path+"/item/"+ id, Item.class);
		
		// 如果返回的是集合类型，则使用如下方式接受
//		Item[] item = restTemplate.getForObject("/item/"+ id, Item[].class);
//		List<Item> list = Arrays.asList(item);
		
		// 使用Ribbon
		String path = "http://czp-mall-item";
		Item item = restTemplate.getForObject(path + "/item/"+ id, Item.class);
		
		
		// 获取调用的服务ip和端口，通过feign的方式获取服务地址
		ServiceInstance serviceInstance = loadBalancerClient.choose("czp-mall-item");
		System.out.println("调用的服务地址端口："+ serviceInstance.getHost() + ":" + serviceInstance.getPort());
		
		return item;
	}
	
}
